import { _decorator, Component, Node, Collider, ITriggerEvent } from 'cc'
import { Constant } from '../framework/Constant'
import { GameManager } from '../framework/GameManager'
import { PoolManager } from '../framework/PoolManager'
const { ccclass, property, menu } = _decorator

/**
 * Predefined variables
 * Name = BulletProp
 * DateTime = Thu Feb 17 2022 14:00:34 GMT+0800 (中国标准时间)
 * Author = ashscc
 * FileBasename = BulletProp.ts
 * FileBasenameNoExtension = BulletProp
 * URL = db://assets/script/bullet/BulletProp.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/en/
 *
 */
const OUT_OF_BACKGROUND_RANGE_Z: number = 50

@ccclass('BulletProp')
@menu('bullet/BulletProp')
export class BulletProp extends Component {
  private _bulletPropSpeed = -0.3
  private _bulletPropXSpeed = 0.3

  private _gameManager: GameManager = null

  onEnable() {
    const collider = this.node.getComponent(Collider)
    collider.on('onTriggerEnter', this._onTriggerEnter, this)
  }

  onDisable() {
    const collider = this.node.getComponent(Collider)
    collider.off('onTriggerEnter', this._onTriggerEnter, this)
  }

  update (deltaTime: number) {
    const pos = this.node.position
    if (pos.x >= 15) {
        this._bulletPropXSpeed =  this._bulletPropSpeed
    }else if (pos.x <= -15) {
        this._bulletPropXSpeed = - this._bulletPropSpeed
    }

    this.node.setPosition(pos.x + this._bulletPropXSpeed, pos.y, pos.z - this._bulletPropSpeed)
    //如果超过摄像机捕捉范围则destroy
    if (this.node.position.z > OUT_OF_BACKGROUND_RANGE_Z) {
      PoolManager.putNode(this.node)
      // this.node.destroy()
    }
  }

  private _onTriggerEnter(event: ITriggerEvent) {
    //子弹改变包只能和玩家飞机碰撞,碰撞以后则消失，同时改变玩家子弹
    const name = event.selfCollider.node.name
    if(name === 'bulletH'){
        this._gameManager.changePlayerBullet(Constant.BulletPropType.BULLET_H)
    }else if(name === 'bulletS'){
        this._gameManager.changePlayerBullet(Constant.BulletPropType.BULLET_S)
    }else {
        this._gameManager.changePlayerBullet(Constant.BulletPropType.BULLET_M)
    }
    PoolManager.putNode(this.node)
    // this.node.destroy()
  }

  public show(gameManager: GameManager, bulletPropSpeed: number){
    this._gameManager = gameManager
    this._bulletPropSpeed = bulletPropSpeed
  }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/en/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/en/scripting/life-cycle-callbacks.html
 */
